import os
from minio import Minio


class MinioUploader:
    def __init__(self, endpoint="localhost:9000", access_key="solex", secret_key="rwwyrywy", bucket_name="solex"):
        self.endpoint = endpoint
        self.access_key = access_key
        self.secret_key = secret_key
        self.bucket_name = bucket_name
        self.client = None
        self._initialize_client()
        
    def _initialize_client(self):
        try:
            self.client = Minio(
                self.endpoint,
                access_key=self.access_key,
                secret_key=self.secret_key,
                secure=False
            )
            # 确保 bucket 存在
            if not self.client.bucket_exists(self.bucket_name):
                self.client.make_bucket(self.bucket_name)
        except Exception as err:
            raise Exception(f"Failed to initialize Minio client: {err}")

    def upload_file(self, file_path, object_name=None):
        """
        上传文件到 MinIO 服务器
        :param file_path: 本地文件路径
        :param object_name: MinIO中的对象名称，如果不指定则使用文件名
        :return: (状态码, 上传后的完整路径)
        """
        try:
            # 如果没有指定object_name，使用文件名
            if object_name is None:
                object_name = os.path.basename(file_path)
                
            # 上传文件
            result = self.client.fput_object(
                self.bucket_name, 
                object_name, 
                file_path
            )
            
            # 返回状态码和完整路径
            full_path = f"http://{self.endpoint}/{self.bucket_name}/{object_name}"
            return 200, full_path
            
        except Exception as err:
            raise Exception(f"Failed to upload file: {err}")

# 使用示例：
if __name__ == "__main__":
    try:
        # 创建上传器实例
        uploader = MinioUploader()
        
        # 上传文件
        file_path = '/Users/tunm/Downloads/snap_800.jpg'
        object_name = 'test02/snap_800.jpg'
        
        # 上传并获取完整路径
        status, full_path = uploader.upload_file(file_path, object_name)
        print(f"File uploaded successfully. Status: {status}, Full path: {full_path}")
        
    except Exception as e:
        print(f"Error: {e}")